﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using SmartMD.DataModel.Entity;
using Techstar.Dialog;
using SmartMD.DataAccess.Service;
using SmartMD.Manager.Common;
using SmartMD.Manager.Utils;

namespace SmartMD.Manager.SysInfo.User
{
    /// <summary>
    /// Interaction logic for UserInfoEdit.xaml
    /// </summary>
    public partial class UserInfoEdit : Window
    {
     #region Properties
        public ObservableCollection<UserInfo> UserInfoList
        {
            get;
            set;
        }
        public UserInfo userInfo { get; set; }
        bool SignAdd = false;
        public delegate void Refresh(UserInfo selectItem);
        public event Refresh refresh;
        private UserManagerWindow myowner;
        #endregion

        public UserInfoEdit(UserManagerWindow owner)
        {
            InitializeComponent();
            this.myowner = owner;
            UserInfoList = new ObservableCollection<UserInfo>();
            this.Loaded += new RoutedEventHandler(DataSourceMetaEdit_Loaded);           
        }

        void DataSourceMetaEdit_Loaded(object sender, RoutedEventArgs e)
        {
            LoadDatabaseMetaInfo();
        }

        /**
         * 功能: 用户输入验证
         * 
         * */
        private bool Validate()
        {
            if (string.IsNullOrEmpty(userInfo.Name))
            {
                TaskDialogEx.Warning("请输入用户名!");
                return false;
            }
            if (string.IsNullOrEmpty(userInfo.Password))
            {
                TaskDialogEx.Warning("请输入密码!");
                return false;
            }
            if (string.IsNullOrEmpty(userInfo.Role))
            {
                TaskDialogEx.Warning("请输入用户角色!");
                return false;
            }

            return true;
            /*  if (Exists(DatabaseMetaInfo.Id, DatabaseMetaInfo.Name))
              {
                  TaskDialogEx.Warning("参数名称重复!");
                  txtName.Focus();
                  return;
              } */
        }
        #region Event
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            userInfo.Id = System.Guid.NewGuid().ToString();
            userInfo.Name = this.txtName.Text;
            userInfo.Password = this.txtPassword.Text;
            userInfo.Department = this.cbxConnectType.Text;
            userInfo.LastModify = System.DateTime.Now;
            //验证输入
            if (!Validate())
                return;
            try
            {
                var result = DataServiceManager.UserService.SaveOrUpdateObject(userInfo);
                if (result)
                {
                    if (SignAdd)
                    {
                        this.myowner.userInfoList.Add(userInfo);
                    }
                 /*   else
                    {
                        var v = (from a in UserInfoList where a.Id == userInfo.Id select a).First();
                        int index = UserInfoList.IndexOf(v);
                        UserInfoList.Remove(v);
                        UserInfoList.Insert(index, userInfo);
                    }
                    if (refresh != null)
                    {
                        refresh(userInfo);
                    } */
                }
                else
                    TaskDialogEx.Warning("保存失败");
            }
            catch (Exception ee)
            {
                TaskDialogEx.Error(ee.Message);
            }

            this.Close();
        }

        private void btnEsc_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void txt_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox txt = sender as TextBox;
            //屏蔽非法按键
            if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
            {
                e.Handled = false;
            }
            else if ((e.Key >= Key.D0 && e.Key <= Key.D9) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }

        }

        private void txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            //屏蔽中文输入和非法字符粘贴输入
            TextBox textBox = sender as TextBox;
            TextChange[] change = new TextChange[e.Changes.Count];
            e.Changes.CopyTo(change, 0);

            int offset = change[0].Offset;
            if (change[0].AddedLength > 0)
            {
                int num = 0;
                if (!int.TryParse(textBox.Text, out num))
                {
                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                    textBox.Select(offset, 0);
                }
            }

        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                btnEsc_Click(null, null);
            }
            if (e.Key == Key.Enter)
            {
                btnOk_Click(null, null);
            }
        }

     
        #endregion

        #region Method
        /// <summary>
        /// 判断是否有重复的NAME
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool Exists(string id, string name)
        {
            return UserInfoList.FirstOrDefault(t => t.Id != id && t.Name.ToLower() == name.ToLower()) != null;
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <returns></returns>
        private void LoadDatabaseMetaInfo()
        {

            this.DataContext = userInfo;
            if (string.IsNullOrEmpty(userInfo.Id))
            {
                this.Title = "添加新用户";
                SignAdd = true;
            }
            else
            {
                this.Title = "编辑用户信息";
            }
        }
        #endregion

        private void cbxConnectType_Initialized(object sender, EventArgs e)
        {
            ComboxUtil.InitializeComboxByDict(sender, "所属科室");
        }
    }
}
